package easytodo.client.ArrayAdapters;

import helpers.StringHelpers;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import easytodo.client.R;
import easytodo.model.Note;

import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class NoteArrayAdapter extends ArrayAdapter<Note> {

	public NoteArrayAdapter(Context context, int textViewResourceId,
			ArrayList<Note> objects) {
		super(context, textViewResourceId, objects);

		theResource = textViewResourceId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		RelativeLayout noteView;
		
		Note item = getItem(position);
		
		Resources resources = getContext().getResources();
		String[] priorities = resources.getStringArray(R.array.priorities);
		
		String priority = priorities[item.PriorityValue];
		
		Date createdDate = new Date(item.Created);
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
		String dateString = sdf.format(createdDate);
		
		CharSequence shortContent = StringHelpers.makePrettyShorterString(
				item.Content, 30, "...");

		if (convertView == null) {
			noteView = new RelativeLayout(getContext());
			String inflater = Context.LAYOUT_INFLATER_SERVICE;
			LayoutInflater vi = (LayoutInflater)getContext().getSystemService(inflater);
			vi.inflate(theResource, noteView, true);
		}
		else {
			noteView = (RelativeLayout) convertView;
		}
		
		TextView titleView = (TextView) noteView.findViewById(R.id.rowTitle);
		TextView shortConventView = (TextView) noteView.findViewById(R.id.rowShortContent);
		TextView createdDateView = (TextView) noteView.findViewById(R.id.rowDate);
		TextView priorityView = (TextView) noteView.findViewById(R.id.rowPriority);
		
		titleView.setText(item.Title);
		shortConventView.setText(shortContent);
		createdDateView.setText(dateString);
		priorityView.setText(priority);
		
		return noteView;
	}

	private int theResource;
}
